import { useTitle } from '@vueuse/core'
import { useUserStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import '@/assets/css/nprogress.css'

NProgress.configure({ showSpinner: false })

/** 路由白名单 */
const ROUTES_WHITE = new Set([
  '/login',
  '/sign-in',
  '/forget-password',
  '/live'
])

/** 默认系统名称 */
const defaultTitle = '虚现体育'

/** @type {import('vue-router').NavigationGuardWithThis<undefined>} */
export default async function (to, from, next) {
  NProgress.start()

  useTitle(to.meta.title ?? defaultTitle)
  // 白名单放行
  if (ROUTES_WHITE.has(to.path)) {
    NProgress.done()
    next()
    return
  }

  try {
    const userStore = useUserStore()
    if (!userStore.user) {
      await userStore.getAndSetUser()
    }
  } catch (error) {
    console.error(error)
    ElMessage.error(error)
    NProgress.done()
    next('/login')
    return
  }

  NProgress.done()
  next()
}
